"""
邮件发送工具模块
"""
import traceback
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
import email.utils
import smtplib
from datetime import datetime
from config.settings import EMAIL_CONFIG


class MailSender:
    """邮件发送器"""
    
    def __init__(self):
        self.config = EMAIL_CONFIG
    
    def send(self, to_addr: str, content: str, subject: str = None, email_type: str = 'notification') -> bool:
        """发送邮件"""
        try:
            if subject is None:
                subject = '杜伊斯堡签证预约系统通知'
            
            # 根据邮件类型创建不同的内容
            if email_type == 'confirmation':
                html_content = self._create_confirmation_email(content)
            elif email_type == 'appointment_success':
                html_content = self._create_success_email(content)
            elif email_type == 'appointment_failed':
                html_content = self._create_failed_email(content)
            else:
                html_content = self._create_notification_email(content)
            
            from_format = email.utils.formataddr(
                (self.config['from_name'], self.config['from_addr'])
            )
            
            msg = MIMEMultipart('alternative')
            msg['From'] = from_format
            msg['To'] = Header(to_addr)
            msg['Subject'] = Header(subject)
            msg['Date'] = email.utils.formatdate(localtime=True)
            
            # 添加HTML内容
            html_part = MIMEText(html_content, 'html', 'utf-8')
            msg.attach(html_part)
            
            server = smtplib.SMTP_SSL(self.config['smtp_server'])
            server.connect(self.config['smtp_server'], self.config['smtp_port'])
            server.login(self.config['from_addr'], self.config['password'])
            server.sendmail(self.config['from_addr'], to_addr, msg.as_string())
            server.quit()
            
            return True
            
        except Exception as e:
            print(f"邮件发送失败: {e}")
            traceback.print_exc()
            return False
    
    def _create_notification_email(self, content: str) -> str:
        """创建通知邮件内容"""
        return f"""
        <!DOCTYPE html>
        <html lang="zh-CN">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>杜伊斯堡签证预约通知</title>
            <style>
                {self._get_base_styles()}
                .notification-card {{
                    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                    color: white;
                    padding: 30px;
                    border-radius: 10px;
                    margin-bottom: 20px;
                }}
                .content-box {{
                    background: #f8f9fa;
                    padding: 20px;
                    border-radius: 8px;
                    border-left: 4px solid #007bff;
                }}
            </style>
        </head>
        <body>
            <div class="email-container">
                <div class="header">
                    <h1>杜伊斯堡签证预约系统</h1>
                    <p class="subtitle">智能预约 · 专业服务</p>
                </div>
                
                <div class="notification-card">
                    <h2>📅 预约时间通知</h2>
                    <p>系统已为您找到可用的预约时间段</p>
                </div>
                
                <div class="content-box">
                    <h3>可用时间段信息：</h3>
                    <p>{content}</p>
                </div>
                
                <div class="footer">
                    <p>此邮件由杜伊斯堡签证预约系统自动发送</p>
                    <p>如有疑问，请联系系统管理员</p>
                </div>
            </div>
        </body>
        </html>
        """
    
    def _create_confirmation_email(self, content: str) -> str:
        """创建确认邮件内容"""
        return f"""
        <!DOCTYPE html>
        <html lang="zh-CN">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>预约申请确认</title>
            <style>
                {self._get_base_styles()}
                .confirmation-card {{
                    background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
                    color: white;
                    padding: 30px;
                    border-radius: 10px;
                    margin-bottom: 20px;
                }}
                .info-section {{
                    background: #ffffff;
                    border: 1px solid #e9ecef;
                    border-radius: 8px;
                    margin: 20px 30px;
                    overflow: hidden;
                }}
                .info-header {{
                    background: #f8f9fa;
                    padding: 15px 20px;
                    border-bottom: 1px solid #e9ecef;
                    font-weight: 600;
                    color: #495057;
                    font-size: 16px;
                }}
                .info-content {{
                    padding: 20px;
                }}
                .info-row {{
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    padding: 12px 0;
                    border-bottom: 1px solid #f1f3f4;
                }}
                .info-row:last-child {{
                    border-bottom: none;
                }}
                .info-label {{
                    font-weight: 500;
                    color: #6c757d;
                    min-width: 80px;
                }}
                .info-value {{
                    color: #212529;
                    font-weight: 400;
                    text-align: right;
                    flex: 1;
                    margin-left: 20px;
                }}
                .confirm-button {{
                    background: linear-gradient(135deg, #007bff 0%, #0056b3 100%);
                    color: white !important;
                    padding: 15px 30px;
                    border-radius: 8px;
                    text-decoration: none;
                    font-weight: bold;
                    font-size: 16px;
                    display: inline-block;
                    margin: 20px 0;
                    box-shadow: 0 4px 15px rgba(0, 123, 255, 0.3);
                    transition: all 0.3s ease;
                }}
                .confirm-button:hover {{
                    transform: translateY(-2px);
                    box-shadow: 0 6px 20px rgba(0, 123, 255, 0.4);
                }}
                @media (max-width: 600px) {{
                    .info-row {{
                        flex-direction: column;
                        align-items: flex-start;
                        gap: 5px;
                    }}
                    .info-value {{
                        text-align: left;
                        margin-left: 0;
                    }}
                }}
            </style>
        </head>
        <body>
            <div class="email-container">
                <div class="header">
                    <h1>杜伊斯堡签证预约系统</h1>
                    <p class="subtitle">请确认您的预约申请</p>
                </div>
                
                <div class="confirmation-card">
                    <h2>✅ 申请确认</h2>
                    <p>您的预约申请已提交，请确认以下信息并点击确认按钮</p>
                </div>
                
                <div class="info-section">
                    <div class="info-header">
                        申请信息
                    </div>
                    <div class="info-content">
                        {content}
                    </div>
                </div>
                
                <div style="text-align: center; margin: 30px 0;">
                    <a href="#" class="confirm-button">确认申请</a>
                </div>
                
                <div class="warning-box">
                    <h4>⚠️ 重要提醒</h4>
                    <ul>
                        <li>此确认链接24小时内有效</li>
                        <li>只有确认后系统才会开始处理您的预约</li>
                        <li>请确保信息准确无误</li>
                    </ul>
                </div>
                
                <div class="footer">
                    <p>此邮件由杜伊斯堡签证预约系统自动发送</p>
                    <p>如果您没有申请此服务，请忽略此邮件</p>
                </div>
            </div>
        </body>
        </html>
        """
    
    def _create_success_email(self, content: str) -> str:
        """创建成功邮件内容"""
        return f"""
        <!DOCTYPE html>
        <html lang="zh-CN">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>预约成功通知</title>
            <style>
                {self._get_base_styles()}
                .success-card {{
                    background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
                    color: white;
                    padding: 30px;
                    border-radius: 10px;
                    margin-bottom: 20px;
                    text-align: center;
                }}
                .success-icon {{
                    font-size: 48px;
                    margin-bottom: 15px;
                }}
                .appointment-details {{
                    background: #f8f9fa;
                    padding: 25px;
                    border-radius: 10px;
                    border: 2px solid #28a745;
                    margin: 20px 0;
                }}
            </style>
        </head>
        <body>
            <div class="email-container">
                <div class="header">
                    <h1>杜伊斯堡签证预约系统</h1>
                    <p class="subtitle">预约成功通知</p>
                </div>
                
                <div class="success-card">
                    <div class="success-icon">🎉</div>
                    <h2>预约成功！</h2>
                    <p>恭喜您，预约已成功完成</p>
                </div>
                
                <div class="appointment-details">
                    <h3>📋 预约详情</h3>
                    {content}
                </div>
                
                <div class="warning-box">
                    <h4>📧 重要提醒</h4>
                    <ul>
                        <li>请检查您的邮箱，外管局会发送确认邮件</li>
                        <li>收到外管局邮件后，请在2小时内点击确认链接</li>
                        <li>请按时到达预约地点，携带所需证件</li>
                    </ul>
                </div>
                
                <div class="footer">
                    <p>此邮件由杜伊斯堡签证预约系统自动发送</p>
                    <p>感谢您使用我们的服务！</p>
                </div>
            </div>
        </body>
        </html>
        """
    
    def _create_failed_email(self, content: str) -> str:
        """创建失败邮件内容"""
        return f"""
        <!DOCTYPE html>
        <html lang="zh-CN">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>预约失败通知</title>
            <style>
                {self._get_base_styles()}
                .failed-card {{
                    background: linear-gradient(135deg, #dc3545 0%, #c82333 100%);
                    color: white;
                    padding: 30px;
                    border-radius: 10px;
                    margin-bottom: 20px;
                    text-align: center;
                }}
                .failed-icon {{
                    font-size: 48px;
                    margin-bottom: 15px;
                }}
                .retry-button {{
                    background: linear-gradient(135deg, #ffc107 0%, #e0a800 100%);
                    color: #212529 !important;
                    padding: 15px 30px;
                    border-radius: 8px;
                    text-decoration: none;
                    font-weight: bold;
                    font-size: 16px;
                    display: inline-block;
                    margin: 20px 0;
                    box-shadow: 0 4px 15px rgba(255, 193, 7, 0.3);
                }}
            </style>
        </head>
        <body>
            <div class="email-container">
                <div class="header">
                    <h1>杜伊斯堡签证预约系统</h1>
                    <p class="subtitle">预约失败通知</p>
                </div>
                
                <div class="failed-card">
                    <div class="failed-icon">😔</div>
                    <h2>预约失败</h2>
                    <p>很抱歉，本次预约未能成功</p>
                </div>
                
                <div class="content-box">
                    <h3>失败原因：</h3>
                    <p>{content}</p>
                </div>
                
                <div style="text-align: center; margin: 30px 0;">
                    <a href="http://localhost:3000" class="retry-button">重新申请</a>
                </div>
                
                <div class="info-box">
                    <h4>💡 建议</h4>
                    <ul>
                        <li>请稍后重新尝试申请</li>
                        <li>可以尝试选择其他时间段</li>
                        <li>如有疑问，请联系系统管理员</li>
                    </ul>
                </div>
                
                <div class="footer">
                    <p>此邮件由杜伊斯堡签证预约系统自动发送</p>
                    <p>我们会继续为您寻找可用的预约时间</p>
                </div>
            </div>
        </body>
        </html>
        """
    
    def _get_base_styles(self) -> str:
        """获取基础样式"""
        return """
            * {
                margin: 0;
                padding: 0;
                box-sizing: border-box;
            }
            body {
                font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
                line-height: 1.6;
                color: #333;
                background-color: #f4f6f9;
            }
            .email-container {
                max-width: 600px;
                margin: 0 auto;
                background: white;
                border-radius: 10px;
                overflow: hidden;
                box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
            }
            .header {
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                color: white;
                padding: 40px 30px;
                text-align: center;
            }
            .header h1 {
                font-size: 28px;
                margin-bottom: 10px;
                font-weight: 300;
            }
            .subtitle {
                font-size: 16px;
                opacity: 0.9;
            }
            .content-box {
                background: #f8f9fa;
                padding: 20px;
                border-radius: 8px;
                border-left: 4px solid #007bff;
                margin: 20px 30px;
            }
            .info-box {
                background: #e3f2fd;
                padding: 20px;
                border-radius: 8px;
                border-left: 4px solid #2196f3;
                margin: 20px 30px;
            }
            .warning-box {
                background: #fff3cd;
                padding: 20px;
                border-radius: 8px;
                border-left: 4px solid #ffc107;
                margin: 20px 30px;
            }
            .warning-box h4 {
                color: #856404;
                margin-bottom: 10px;
            }
            .warning-box ul {
                color: #856404;
                padding-left: 20px;
            }
            .footer {
                background: #f8f9fa;
                padding: 30px;
                text-align: center;
                color: #6c757d;
                font-size: 14px;
                border-top: 1px solid #dee2e6;
            }
            .footer p {
                margin: 5px 0;
            }
            @media (max-width: 600px) {
                .email-container {
                    margin: 0;
                    border-radius: 0;
                }
                .header, .content-box, .info-box, .warning-box, .footer {
                    margin-left: 15px;
                    margin-right: 15px;
                }
            }
        """
    
    def send_notification(self, content: str) -> bool:
        """发送通知邮件"""
        return self.send(self.config['to_addr'], content, email_type='notification')
    
    def send_confirmation(self, to_addr: str, user_data: dict, confirmation_url: str) -> bool:
        """发送确认邮件"""
        # 构建用户信息HTML - 使用简洁的表格样式
        phone_section = ""
        if user_data.get('phone'):
            phone_section = f"""
        <div class="info-row">
            <span class="info-label">电话</span>
            <span class="info-value">{user_data.get('phone', '')}</span>
        </div>"""
        
        info_html = f"""
        <div class="info-row">
            <span class="info-label">称呼</span>
            <span class="info-value">{user_data.get('anrede', '')}</span>
        </div>
        <div class="info-row">
            <span class="info-label">姓名</span>
            <span class="info-value">{user_data.get('first_name', '')} {user_data.get('last_name', '')}</span>
        </div>
        <div class="info-row">
            <span class="info-label">邮箱</span>
            <span class="info-value">{user_data.get('email', '')}</span>
        </div>
        <div class="info-row">
            <span class="info-label">生日</span>
            <span class="info-value">{user_data.get('birthday', '')}</span>
        </div>{phone_section}
        <div class="info-row">
            <span class="info-label">申请服务</span>
            <span class="info-value">{user_data.get('service', '')}</span>
        </div>
        """
        
        # 创建确认邮件内容，并替换确认按钮的链接
        confirmation_content = self._create_confirmation_email(info_html)
        confirmation_content = confirmation_content.replace('href="#"', f'href="{confirmation_url}"')
        
        subject = f"杜伊斯堡签证预约确认 - {user_data.get('first_name', '')} {user_data.get('last_name', '')}"
        
        # 直接发送HTML内容，不通过send方法的模板处理
        try:
            from_format = email.utils.formataddr(
                (self.config['from_name'], self.config['from_addr'])
            )
            
            msg = MIMEMultipart('alternative')
            msg['From'] = from_format
            msg['To'] = Header(to_addr)
            msg['Subject'] = Header(subject)
            msg['Date'] = email.utils.formatdate(localtime=True)
            
            # 添加HTML内容
            html_part = MIMEText(confirmation_content, 'html', 'utf-8')
            msg.attach(html_part)
            
            server = smtplib.SMTP_SSL(self.config['smtp_server'])
            server.connect(self.config['smtp_server'], self.config['smtp_port'])
            server.login(self.config['from_addr'], self.config['password'])
            server.sendmail(self.config['from_addr'], to_addr, msg.as_string())
            server.quit()
            
            return True
            
        except Exception as e:
            print(f"确认邮件发送失败: {e}")
            return False
    
    def send_appointment_success(self, to_addr: str, appointment_details: str) -> bool:
        """发送预约成功邮件"""
        subject = "预约成功通知 - 杜伊斯堡签证预约系统"
        return self.send(to_addr, appointment_details, subject, 'appointment_success')
    
    def send_appointment_failed(self, to_addr: str, failure_reason: str) -> bool:
        """发送预约失败邮件"""
        subject = "预约失败通知 - 杜伊斯堡签证预约系统"
        return self.send(to_addr, failure_reason, subject, 'appointment_failed')


# 全局邮件发送器实例
mail_sender = MailSender()
